package tsinghua.smxq.mc;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import tsinghua.smxq.foodprice.TimeFormatTransform;
import tsinghua.smxq.utilitiespayment.MoneyandMoneyId;
import tsinghua.smxq.utilitiespayment.Record;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

public class BankActivity extends TabActivity {
	// 自定义
	private TabHost mytabhost = null; // 定义TabHost
	TextView userInfo_textview, bill_textview;
	Button getback_button;
	String cardNum = ""; // 卡号
	String password = ""; // 密码
	float money = 0.0f; // 账户余额
	int type = 0;
	String[] billtype;
	Record record;
	private Toast toast;
	int status; // 表示是否缴费成功

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// 获得传过来的值
		record = new Record();
		cardNum = getIntent().getStringExtra("cardNum");
		password = getIntent().getStringExtra("password");
		money = Float.valueOf(getIntent().getStringExtra("money"));
		type = getIntent().getIntExtra("type", 0);
		record.recordId = getIntent().getStringExtra("recordId");
		record.cityId = getIntent().getStringExtra("cityId");
		record.month = getIntent().getIntExtra("month", 1);
		record.usage = getIntent().getFloatExtra("usage", 0.0f);
		record.unitprice = getIntent().getFloatExtra("unitprice", 0.0f);
		record.rate = getIntent().getFloatExtra("rate", 0.0f);
		mytabhost = super.getTabHost(); // 取得TabHost对象
		LayoutInflater.from(this) // 取得LayoutInflater对象
				.inflate(R.layout.activity_bank, // 定义转换的布局管理器
						this.mytabhost.getTabContentView(), // 指定标签增加的容器
						true); // 实例化布局管理器中的组件
		billtype = new String[] { "水费", "电费" };
		userInfo_textview = (TextView) findViewById(R.id.userInfo_textview);
		userInfo_textview.setText("银行卡号： " + cardNum + "\n密码：  " + password
				+ "\n账户余额:" + money);
		getback_button = (Button) findViewById(R.id.getback_button);
		getback_button.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View arg0) {
				Intent gotoIntent = new Intent(BankActivity.this,
						RecordsActivity.class);
				BankActivity.this.startActivity(gotoIntent);
			}
		});
		TabSpec InfoTab = mytabhost.newTabSpec("info"); // 定义TabSpec
		InfoTab.setIndicator("用户信息"); // 设置标签文字
		InfoTab.setContent(R.id.tab_userInfo); // 设置显示的组件
		this.mytabhost.addTab(InfoTab); // 增加标签

		bill_textview = (TextView) findViewById(R.id.billId_textview);
		bill_textview.setText(billtype[type] + "订单\n" + "编号为："
				+ record.recordId);
		bill_textview.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showInfoDialog();

			}
		});

		TabSpec PayTab = mytabhost.newTabSpec("pay"); // 定义TabSpec
		PayTab.setIndicator("支付账单"); // 设置标签文字
		PayTab.setContent(R.id.tab_bills); // 设置显示的组件
		this.mytabhost.addTab(PayTab); // 增加标签

	}

	public void showInfoDialog() {
		AlertDialog.Builder adb = new AlertDialog.Builder(this)
				/** 设置标题 **/
				.setTitle("详细信息")
				/** 设置icon **/
				.setIcon(android.R.drawable.alert_dark_frame)
				/** 设置内容 **/
				.setMessage(
						"账单编号：" + record.recordId + "\n缴费类型：" + billtype[type]
								+ "\n用户编号：" + Session.user.getId() + "\n城市编号："
								+ record.cityId + "\n月份：" + record.month
								+ "\n数量：" + record.usage + "\n单价："
								+ record.unitprice + "\n总额：" + record.rate);
		adb.setNegativeButton("关闭", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		adb.setPositiveButton("支付", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

				DisplayToast("正在支付... ...", Toast.LENGTH_SHORT);
				// 连接服务器，支付账单
				try {
					PayAction();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		adb.show();
	}

	public void DisplayToast(String str, int time) {
		toast = Toast.makeText(this, str, Toast.LENGTH_SHORT);
		// 设置toast显示的位置
		toast.setGravity(Gravity.TOP, 0, 320);
		// 显示该Toast
		toast.show();
	}

	public void PayAction() throws URISyntaxException, ClientProtocolException,
			IOException, JSONException {
		HttpClient httpclient = new DefaultHttpClient();
		ArrayList<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(new BasicNameValuePair("method", "createPayRecord"));
		qparams.add(new BasicNameValuePair("userid", String
				.valueOf(Session.user.getId())));
		qparams.add(new BasicNameValuePair("recordid", record.recordId));
		qparams.add(new BasicNameValuePair("amount", String
				.valueOf(record.rate)));
		qparams.add(new BasicNameValuePair("merfeeamt", "0"));
		qparams.add(new BasicNameValuePair("curtype", "3"));
		qparams.add(new BasicNameValuePair("merid", record.cityId));
		qparams.add(new BasicNameValuePair("meracct", "1234567890123456780"));
		qparams.add(new BasicNameValuePair("customcardnum", cardNum));
		qparams.add(new BasicNameValuePair("remark", "" + type));
		URI uri = URIUtils.createURI("http", Constants.serverIP, 8080,
				"MobileCityServer/ICBCINBSEBusinessServlet",
				URLEncodedUtils.format(qparams, "UTF-8"), null);
		HttpGet httpget = new HttpGet(uri);
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			String contentString = EntityUtils.toString(entity);
			JSONObject o = new JSONObject(contentString);
			status = o.getInt("status");
			if (status == -1) {
				DisplayToast("缴费失败...", Toast.LENGTH_SHORT);
			} else {
				showInfoDialog(o.getString("payRecord"));
				bill_textview.setText("");
				bill_textview.setClickable(false);

			}
		}

	}

	// 查看详细信息
	protected void showInfoDialog(String tolook) {
		AlertDialog.Builder adb = new AlertDialog.Builder(this)
		/** 设置标题 **/
		.setTitle("账单详情")
		/** 设置icon **/
		.setIcon(android.R.drawable.alert_dark_frame)
		/** 设置内容 **/
		.setMessage(tolook);
		adb.setNegativeButton("关闭", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		adb.show();
	}

	// 查看详细信息
	protected void showInfoDialog(int id, int recordId, String tranSerialNo,
			int amount, int merFeeAmt, int curType, int merId, String merAcct,
			String customCardNum, int remark) {
		AlertDialog.Builder adb = new AlertDialog.Builder(this)
				/** 设置标题 **/
				.setTitle("账单详情")
				/** 设置icon **/
				.setIcon(android.R.drawable.alert_dark_frame)
				/** 设置内容 **/
				.setMessage(
						"id：\t" + id + "\n账单编号：\t" + recordId + "\n用户编号：\t"
								+ Session.user.getId() + "\n缴费单序列号：\t"
								+ tranSerialNo + "\n数量：\t" + amount
								+ "\n商城收费：\t" + merFeeAmt + "\n支付币种：\t"
								+ MoneyandMoneyId.getMoney(curType)
								+ "\n商城代码:\t" + merId + "\n商城账号：\t" + merAcct
								+ "\n付款账号：\t" + customCardNum + "\n付款时间：\t"
								+ TimeFormatTransform.getCurrentDate_Blank()
								+ "\n注：\t" + remark);
		adb.setNegativeButton("关闭", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		adb.show();
	}

	// 查看详细信息
	protected void showInfoDialog(Object id, Object recordId,
			Object tranSerialNo, Object amount, Object merFeeAmt,
			Object curType, Object merId, Object merAcct, Object customCardNum,
			Object remark) {
		AlertDialog.Builder adb = new AlertDialog.Builder(this)
				/** 设置标题 **/
				.setTitle("账单详情")
				/** 设置icon **/
				.setIcon(android.R.drawable.alert_dark_frame)
				/** 设置内容 **/
				.setMessage(
						"id：\t" + id + "\n账单编号：\t" + recordId + "\n用户编号：\t"
								+ Session.user.getId() + "\n缴费单序列号：\t"
								+ tranSerialNo + "\n数量：\t" + amount
								+ "\n商城收费：\t" + merFeeAmt + "\n支付币种：\t"
								+ curType + "\n商城代码:\t" + merId + "\n商城账号：\t"
								+ merAcct + "\n付款账号：\t" + customCardNum
								+ "\n付款时间：\t"
								+ TimeFormatTransform.getCurrentDate_Blank()
								+ "\n注：\t" + remark);
		adb.setNegativeButton("关闭", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		adb.show();
	}

}